package time_task

import (
	. "chess_platform/internal/common"
	"fmt"
)

//每天凌晨执行，统计昨天的数据
//统计每天每款游戏开的桌子数和小局数
func StatDayChess(r map[int64]int64) error {
	return ForExecute(listAllChess, RecordDayChess, r[RecordDayChess])
}

func listAllChess(t int64) error {
	LogPc.Info("----------------------进入统计局数---------------------------")
	type ChessStat struct {
		TableNum int64 `json:"table_num"` //桌子数
		RoundNum int64 `json:"round_num"` //小局数
		Diamond  int64 `json:"diamond"`   //消耗的钻石数
		GameType int64 `json:"game_type"`
		PlayType int64 `json:"play_type"`
	}
	var cs []ChessStat
	start, end := StartEndTimeByTimestamp(t)

	sql := fmt.Sprintf(`
		SELECT
			COUNT(1) AS table_num,IF (SUM(p.curround) is NULL,0,SUM(p.curround)) AS round_num,
			IF (SUM(p.fee) is NULL,0,SUM(p.fee)) AS diamond,
			p.gametype AS game_type,p.playtype AS play_type
		FROM
			%v AS p
		WHERE
			p.endtime >= %v AND p.endtime <= %v
		GROUP BY p.gametype,p.playtype
	`, TableRoom, start, end)
	sqlUser := fmt.Sprintf(`
		SELECT
			COUNT(DISTINCT r.uid) AS user_num
		FROM
			%v AS p
		LEFT JOIN
			%v AS r
		ON p.tableid = r.tableid
		WHERE
			p.endtime >= %v AND p.endtime <= %v AND p.gametype = ? AND p.playtype = ?
	`, TableRoom, TableRoomLog, start, end)
	o := NewDBOrm(DBChess)
	_, err := o.Raw(sql).QueryRows(&cs)
	if err != nil {
		LogPc.Error(fmt.Sprintf("统计每天每款游戏时出错:%v", err))
		return err
	}
	allGame := listGame()
	gameMap := make(map[int64]bool, len(allGame))
	for _, v := range allGame {
		gameMap[v] = false
	}

	for _, v := range cs {
		var userNum int64
		o.Raw(sqlUser, v.GameType, v.PlayType).QueryRow(&userNum)
		gameId := GenGameId(v.GameType, v.PlayType)
		data := map[string]interface{}{
			"create_time": end - 1,
			"game_id":     gameId,
			"table_num":   v.TableNum,
			"round_num":   v.RoundNum,
			"diamond":     v.Diamond,
			"user_num":    userNum,
		}
		_, err := NewOrUpdateChessLog(data, TableDayGameStat)
		if err != nil {
			LogPc.Error(fmt.Sprintf("写入表:%v时出错:%v", TableDayGameStat, err))
			return err
		}
		_, ok := gameMap[gameId]
		if ok {
			gameMap[gameId] = true
		}
	}
	for k, v := range gameMap {
		if v == true {
			continue
		}
		data := map[string]interface{}{
			"create_time": end - 1,
			"game_id":     k,
			"table_num":   0,
			"round_num":   0,
			"diamond":     0,
			"user_num":    0,
		}
		_, err := NewOrUpdateChessLog(data, TableDayGameStat)
		if err != nil {
			LogPc.Error(fmt.Sprintf("写入表:%v时出错:%v", TableDayGameStat, err))
			return err
		}
	}

	LogPc.Info("----------------------退出统计局数---------------------------")
	return nil
}

//获取游戏列表
func listGame() []int64 {
	sql := fmt.Sprintf(`
		SELECT
			game_id
		FROM
			%v
		WHERE
			is_publish = 1
		`, TableGameList)
	o := NewDBOrm(DBChessSysData)
	var gl []int64
	_, err := o.Raw(sql).QueryRows(&gl)
	if CheckError(err) {
		LogPc.Error(fmt.Sprintf("获取全部上线的游戏失败:%v", err))
		return gl
	}
	return gl
}
